// Copyright (c) 2024 Cloudflare, Inc.
// Licensed under the Apache 2.0 license found in the LICENSE file or at:
//     https://opensource.org/licenses/Apache-2.0

function base64ToBlob(base64, mimeType) {
  const binaryString = atob(base64); // Decode Base64
  const len = binaryString.length;
  const bytes = new Uint8Array(len);
  for (let i = 0; i < len; i++) {
    bytes[i] = binaryString.charCodeAt(i);
  }
  return new Blob([bytes], { type: mimeType });
}

export default {
  async fetch(request, env, ctx) {
    const url = new URL(request.url);

    if (url.pathname === '/to-everything/markdown/transformer') {
      const body = await request.json();
      const decoder = new TextDecoder('utf-8');

      const result = [];

      for (const file of body.files) {
        if (file.name === 'headers.md') {
          const newHeaders = new Headers(request.headers);
          newHeaders.delete('content-length');
          result.push({
            name: file.name,
            mimeType: file.mimeType,
            format: 'markdown',
            tokens: 0,
            data: Object.fromEntries(newHeaders.entries()),
          });
        } else {
          const fileblob = await base64ToBlob(file.data, file.mimeType);
          const arr = await fileblob.arrayBuffer();
          result.push({
            name: file.name,
            mimeType: file.mimeType,
            format: 'markdown',
            tokens: 0,
            data: decoder.decode(arr),
          });
        }
      }

      return Response.json({
        success: true,
        result: result,
      });
    }

    if (url.pathname === '/to-everything/markdown/supported') {
      return Response.json({
        success: true,
        result: [
          {
            extension: '.md',
            mimeType: 'text/markdown',
          },
          {
            extension: '.png',
            mimeType: 'image/png',
          },
        ],
      });
    }
  },
};
